import key from 'keymaster'

import { asyncTopicConstants } from '../constants/asyncTopicConstants'
import { syncTopicConstants } from '../constants/syncTopicConstants'

import * as service from '../utils/request'


const GlobalModel = {
    namespace: 'panelModel',
    state: {
        searchResult: [],                     // 当前搜索结果
        cursor: 0,                            // searchResult的游标
        relativeCursor: 1,
        searchDataSource: "pluginDefine",     // configDefine:搜索结果来自配置定义或动态生成，动态生成通常是list模式下的搜索结果
        listPluginInfo: null,                 // 当前listPlugin详细信息
        searchActionInfo: null,               // 当前用户搜索的相关信息
        preprocessForPanel: null,             // 预搜索的显示内容

    },
    effects: {




        *doRunPluginByBackend({ payload, callback }, { call, put, select }) {
            const { searchDataSource, searchActionInfo } = yield select(state => state.listModel)
            const plugin = payload.plugin
            if (searchDataSource == "pluginDefine") {
                // 执行doRunPluginByPluginDefine
                const pluginInfo = plugin.extInfo.cmdDetailInfo
                const thePayload = {
                    plugin: pluginInfo,
                    input: searchActionInfo.input,
                    subInput: searchActionInfo.subInput,
                    extInfo: searchActionInfo.extInfo,
                    type: searchActionInfo.iconType,
                    source: "hover"
                }
                service.onEmit(asyncTopicConstants.doRunPlugin, thePayload)

            }

            service.onEmit(asyncTopicConstants.hideMainForPanel)
            yield put({ type: "save", payload: { searchResult: [], preprocessForPanel: null } })
        },



        *updateMainWinHeight({ payload, callback }, { call, put, select }) {
            let cnt = yield select(state => state.panelModel.searchResult.length)
            if (cnt > 5) {
                cnt = 5
            }
            // 窗口高度=插件高度*40+标题区+预处理插件区高度（翻译等）
            let height = cnt * 40 + 50 + 5
            const preprocessForPanel = yield select(state => state.panelModel.preprocessForPanel)

            if (preprocessForPanel != null) {
                if (preprocessForPanel.type == "translate") {
                    height = height + Math.ceil(preprocessForPanel.data.to.length / 30) * 25
                }
            }

            service.onEmit(asyncTopicConstants.setPanelHeight, height)
        },




    },
    reducers: {
        save(state, { payload }) {
            return { ...state, ...payload };
        },

        // compose搜索结果，转换为列表
        doMergeSeachResult(state, { payload }) {
            const resultData = []
            for (let item of payload.searchResult) {
                resultData.push(
                    {
                        key: item.cmdId,
                        featureIcon: item.cmdInfo?.featureInfo.icon,
                        featureName: item.cmdInfo?.featureInfo.name,
                        pluginName: item.cmdInfo?.pluginInfo.pluginInfo.name,
                        featureDesc: item.cmdInfo?.featureInfo.desc,
                        extInfo: { cmdDetailInfo: item }
                    }
                )
            }
            // 如果为异步搜索则使用 [...state.searchResult, ...resultData]
            const searchResult = resultData
            let hash = {}
            const newArr = searchResult.reduceRight((item, next) => {
                hash[next.key] ? '' : hash[next.key] = true && item.push(next);
                return item
            }, []);

            // 保存数据并初始化列表的选择游标
            return { ...state, searchResult: newArr, cursor: 0, relativeCursor: 1 };
        },

        // 重置搜索列表结果
        doResetSeachResult() {
            return { ...state, searchResult: [], cursor: 0, relativeCursor: 1, preSearch: null };
        },


    },
    subscriptions: {
        // 预搜索结果监听
        onPreprocessForPanel({ dispatch }) {
            return service.onListen(asyncTopicConstants.onPreProcessForPanel,
                (response) => {
                    if (response.success == true) {
                        dispatch({ type: 'save', payload: { preprocessForPanel: response.body } })
                    }
                }
            )
        },


        // 监听搜索结果消息
        onSearchPluginForPanel({ dispatch }) {
            return service.onListen(asyncTopicConstants.onSearchPluginForPanel,
                (response) => {
                    if (response.success == true) {
                        // 组装数据
                        dispatch({
                            type: 'doMergeSeachResult', payload: {
                                searchResult: response.body.cmdInfos,
                            }
                        })
                        // 根据组装后的数据设置窗口高度

                    }
                    dispatch({ type: 'updateMainWinHeight' })
                }
            )
        },

        onSearchListReset({ dispatch }) {
            return service.onListen(asyncTopicConstants.resetSearchPlugin,
                (response) => {
                    if (response.success == true) {
                        // 组装数据
                        dispatch({ type: 'doResetSeachResult' })
                        // 根据组装后的数据设置窗口高度
                        dispatch({ type: 'updateMainWinHeight' })
                    }
                }
            )
        },



        /*
        * desc: 清空搜索列表
        */
        onEmptySearchResult({ dispatch }) {
            return service.onListen(asyncTopicConstants.doEmptySearchResult,
                (response) => {
                    dispatch({ type: 'doEmptySearchResult' })
                }
            )
        },




    }


};


export default GlobalModel;
